package com.yzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzg.pojo.UserRole;
import com.yzg.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzg.mapper.RoleMapper;
import com.yzg.pojo.Role;
import com.yzg.service.RoleService;
import org.springframework.util.StringUtils;

/**
* @Author: decade
* @Description: ${description}
* @Date: 2021/1/14 20:49
**/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleService userRoleService;
    //根据用户id获取角色数据
    @Override
    public Map<String, Object> findRoleByUserId(String userId) {
        //查询所有角色
        List<Role> allRolesList = baseMapper.selectList(null);

        //根据用户id查询用户拥有的角色id
        List<UserRole> existUserRoleList = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", userId).select("role_id"));
        List<String> existRoleList = existUserRoleList.stream().map(c->c.getRoleId()).collect(Collectors.toList());

        //对角色进行分类
        List<Role> assignRoles = new ArrayList<Role>();
        for(Role role : allRolesList){
            if(existRoleList.contains(role.getId())){
                assignRoles.add(role);
            }
        }
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assignRoles", assignRoles);
        roleMap.put("allRolesList", allRolesList);
        return roleMap;
    }

    //根据用户分配角色
    @Override
    public void saveUserRoleRealtionShip(String userId, String[] roleIds) {
        //先删除原来的，再添加
        //先删除本来的
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", userId));

        List<UserRole> userRoleList = new ArrayList<>();
        for(String roleId : roleIds){
            if(StringUtils.isEmpty(roleId)) continue;
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        }
        userRoleService.saveBatch(userRoleList);
    }
}
